package cn.k.controller;

import cn.k.domain.Permission;
import cn.k.domain.Role;
import cn.k.qo.QueryObject;
import cn.k.service.IPermissionService;
import cn.k.service.IRoleService;
import cn.k.util.RequirePermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    //处理分页查询页面请求
    @RequestMapping("/list")
    @RequirePermission(name = "角色查询",expression = "role:list")
    public String list(QueryObject qo, Model model){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "role/list";
    }


    //处理删除请求
    @RequirePermission(name = "角色删除",expression = "role:delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id!=null){
            roleService.delete(id);
        }
        return "redirect:/role/list";
    }

    //处理添加或者更新的请求,跳转页面
    @RequestMapping("/input")
    @RequirePermission(name = "角色编辑",expression = "role:saveOrUpdate")
    public String input(Long id,Model model){
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions",permissions);
        //修改,带id值
        if (id !=null){
            model.addAttribute("role",roleService.get(id));
            //查询被编辑的角色的所具有的权限
            List<Permission> havePermissions=permissionService.queryByRoleId(id);
            model.addAttribute("havePermissions",havePermissions);

        }
        return "role/input";
    }

    //处理添加或者更新的请求
    @RequestMapping("/saveOrUpdate")
    @RequirePermission(name = "角色编辑",expression = "role:saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] permissionIds){
        //判断有没有id
        if (role.getId()==null){
            roleService.save(role,permissionIds);
        }else {
            roleService.update(role,permissionIds);
        }
        return "redirect:/role/list";
    }


}
